﻿ReplaceEnv(string)
{
    Global g_qzConfig, g_qzExternalVar 
    if strlen(g_qzConfig.setting.UserEnv_File)  And (Not IsObject(g_qzExternalVar))
        ExternalUserEnv()
    ; 利用正则找出字符串中所有的 %var% 
    p1 := 1
    r := ""
    Loop 
    {
      p2 := RegExMatch(string,"%[^%]*%",m,p1)
      RString := ""
      If Not p2 
      {
        If P1 > 1
          r .= over
        Else
          r := string
        Break
      }
      Else If Strlen(m)
      {
          ; 去掉找到的 %var% 两侧的 %
          env := SubStr(m,2,strlen(m)-2)
          if StrLen(g_qzExternalVar[Env])
              RString := g_qzExternalVar[env] ; 配置文件中定义的用户变量
          else if StrLen(g_qzConfig.user_env[env])
              RString := g_qzConfig.user_env[env] ; 配置文件中定义的用户变量
          else if RegExMatch(env,"i)(^apps$)|(^plugins$)|(^icons$)",MZVar)
              RString := A_ScriptDir "\" MZVar ; 预定义的路径
          else if RegExMatch(env,"i)^a_")
              RString := %env% ; AHK内置变量
          else if StrLen(sys := ReplaceEnv_Get(env))
              RString := sys ; 环境变量
          else
              RString := m 
      }
      if Strlen(RString)
          EnvListSet(Env, RString)
      inter := SubStr(string,p1,p2-p1)
      p1 := p2 + Strlen(m)
      over := SubStr(string,p1)
      r .= inter RString
    }
    Return r
}
ReplaceEnv_Get(aEnv)
{
    EnvGet, rVar, %aEnv%
    return rVar
}

ExternalUserEnv()
{
    Global g_qzConfig, g_qzExternalVar 
    ExVarFile := g_qzConfig.Setting.UserEnv_File
    If FileExist(ExVarFile)
    {
        g_qzExternalVar := {}
        FileRead, Var, %ExVarFile%
        Loop, Parse, Var, `n, `r
        {
            If (not Strlen(A_LoopField)) or RegexMatch(A_LoopField, "^[\t\s]*`;")
                Continue
            g_qzExternalVar[Regexreplace(A_LoopField, "=.*$")] := Regexreplace(A_LoopField, "^[^=]*=")
        }
    }
}

EnvListClear()
{
    Global g_qzEnvList
    g_qzEnvList := {}
}

EnvListSet(pEnv, pValue)
{
    Global g_qzEnvList
    if not IsObject(g_qzEnvList)
        g_qzEnvList := {}
    g_qzEnvList[pValue] := pEnv
}

EnvListSearch(pString)
{
    Global g_qzEnvList
    strReturn := pString
    for iValue , iEnv in g_qzEnvList
    {
        if RegExMatch(pString, ToMatch(iValue))
            strReturn := RegExReplace(strReturn, ToMatch(iValue), "%" iEnv "%")
    }
    return strReturn
}
